package com.tianji.promotion.task;

import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.enums.ObtainType;
import com.tianji.promotion.service.ICouponScopeService;
import com.tianji.promotion.service.ICouponService;
import com.tianji.promotion.service.IExchangeCodeService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

import static com.tianji.promotion.enums.CouponStatus.ISSUING;
import static com.tianji.promotion.enums.CouponStatus.UN_ISSUE;

@Component
@RequiredArgsConstructor
public class AutoIssueCoupon {
    private final ICouponService couponService;
    private final IExchangeCodeService codeService;

    @XxlJob("couponIssueJobHandler")
    public void autoIssueCoupon() {
        int shardIndex = XxlJobHelper.getShardIndex();
        int shardTotal = XxlJobHelper.getShardTotal();

        // 1.查询未开始的优惠券
        List<Coupon> couponList = couponService.lambdaQuery()
                .eq(Coupon::getStatus, UN_ISSUE)
                .eq(Coupon::getObtainWay, ObtainType.ISSUE)
                .le(Coupon::getIssueBeginTime, LocalDateTime.now())
                .list();

        // 2.遍历优惠券，进行发放
        for (Coupon coupon : couponList) {
            coupon.setStatus(ISSUING);
            codeService.asyncGenerateCode(coupon);
        }
        couponService.updateBatchById(couponList);

    }
}
